<script setup>
import { ref, reactive, onMounted } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { queryConsumePageApi } from '@/api/consume'
import { queryTrendApi, queryPieApi, queryMerchantTypepi } from '@/api/statistics'
import { merchantTypes, ensureMerchantTypes } from '@/shared/merchantTypes'

// 筛选表单（复用现有查询参数结构）
const searchForm = reactive({
  year: new Date().getFullYear().toString(), // 默认当前年份
  merchantType: '',
  abnormalStatus: '',
  page: 1,
  pageSize: 100,
})

const loading = ref(false)
const monthLabels = ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月']

// 动态商户类型选项（基于查询结果生成）
const merchantTypeOptions = ref([])

// 模拟数据开关与基础类型
const useMock = ref(true)
const baseMerchantTypes = ['餐饮','超市','书店','校内服务','网购']

// 图表视图与饼图时间选择（年、月分开）
const chartView = ref('trend')
const pieYear = ref(new Date().getFullYear().toString())
const pieMonthNum = ref('') // '1'..'12'，空表示未选月份
// 图表实例引用
let trendChart
let pieAmountChart
let pieCountChart

const ensureYearSelected = () => {
  if (!searchForm.year) {
    ElMessage.error('请先选择统计年份')
    return false
  }
  return true
}

// 初始化与渲染图表
const renderTrendChart = (amountByMonth, countByMonth) => {
  const colors = ['#5070dd', '#b6d634']
  if (!trendChart) {
    trendChart = echarts.init(document.getElementById('trendChart'))
    window.addEventListener('resize', () => trendChart && trendChart.resize())
  }
  trendChart.setOption({
    color: colors,
    tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } },
    grid: { right: '10%', left: '6%', bottom: '8%', top: '12%' },
    toolbox: { feature: { dataView: { show: true, readOnly: false }, restore: { show: true }, saveAsImage: { show: true } } },
    legend: { data: ['总笔数', '总金额'] },
    xAxis: [{ type: 'category', axisTick: { alignWithLabel: true }, data: monthLabels }],
    yAxis: [
      { type: 'value', name: '总笔数', position: 'right', axisLine: { show: true, lineStyle: { color: colors[0] } }, axisLabel: { formatter: '{value} 笔' } },
      { type: 'value', name: '总金额', position: 'left', axisLine: { show: true, lineStyle: { color: colors[1] } }, axisLabel: { formatter: '{value} 元' } },
    ],
    series: [
      { name: '总笔数', type: 'bar', yAxisIndex: 0, data: countByMonth },
      { name: '总金额', type: 'line', yAxisIndex: 1, data: amountByMonth },
    ]
  })
}

const renderPie = (domId, title, data, unit) => {
  const chart = echarts.init(document.getElementById(domId))
  window.addEventListener('resize', () => chart && chart.resize())
  chart.setOption({
    tooltip: { trigger: 'item', formatter: (p) => `${p.name}: ${p.value} ${unit} (${p.percent}%)` },
    legend: { top: '5%', left: 'center' },
    title: { text: title, left: 'center', top: 0 },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        padAngle: 3,
        itemStyle: { borderRadius: 10 },
        label: { show: false, position: 'center' },
        emphasis: { label: { show: true, fontSize: 18, fontWeight: 'bold', formatter: (p) => `${p.name}\n${p.value} ${unit}` } },
        labelLine: { show: false },
        data
      }
    ]
  })
  return chart
}

const fetchTrendStats = async () => {
  if (!ensureYearSelected()) return { amountByMonth: Array(12).fill(0), countByMonth: Array(12).fill(0) }
  loading.value = true
  try {
    const res = await queryTrendApi({
      year: searchForm.year,
      merchantType: searchForm.merchantType || '',
      abnormalStatus: searchForm.abnormalStatus || '',
    })
    const d = res?.data || {}
    const amountByMonth = Array.isArray(d.amountByMonth) ? d.amountByMonth : Array(12).fill(0)
    const countByMonth = Array.isArray(d.countByMonth) ? d.countByMonth : Array(12).fill(0)
    return { amountByMonth, countByMonth }
  } finally {
    loading.value = false
  }
}

const fetchPieStats = async () => {
  loading.value = true
  try {
    const params = {}
    if (pieYear.value) params.year = pieYear.value
    if (pieMonthNum.value) params.month = pieMonthNum.value
    if (searchForm.abnormalStatus && searchForm.abnormalStatus !== '') {
      params.abnormalStatus = searchForm.abnormalStatus === '0' ? 0 : 1
    }
    const res = await queryPieApi(params)
    const d = res?.data || {}
    const amountData = Array.isArray(d.amountByMonth) ? d.amountByMonth : []
    const countData = Array.isArray(d.countByMonth) ? d.countByMonth : []
    return { amountData, countData }
  } finally {
    loading.value = false
  }
}

const onSearch = async () => {
  // 折线图直接调用后端聚合接口
  if (chartView.value === 'trend') {
    const { amountByMonth, countByMonth } = await fetchTrendStats()
    renderTrendChart(amountByMonth, countByMonth)
    return
  }

  // 饼图：后端聚合接口
  const { amountData, countData } = await fetchPieStats()
  pieAmountChart = renderPie('pieAmountChart', '商户类型金额占比', amountData, '元')
  pieCountChart = renderPie('pieCountChart', '商户类型笔数占比', countData, '笔')
}

const getMerchantTypes = async () => {
  loading.value = true
  try {
    await ensureMerchantTypes()
    merchantTypeOptions.value = merchantTypes.value
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getMerchantTypes()
  onSearch()
})
</script>

<template>
  <div class="report-page">
    <div class="container">
      <h1>消费数据图表统计</h1><br></br>
      <el-form :model="searchForm" label-width="80px" class="search-form" inline @keyup.enter="onSearch">
        <el-form-item label="图表类型">
          <el-radio-group v-model="chartView" @change="onSearch">
            <el-radio-button label="trend">折线图</el-radio-button>
            <el-radio-button label="pie">饼状图</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="统计年份" v-show="chartView==='trend'" required>
          <el-date-picker
            v-model="searchForm.year"
            type="year"
            placeholder="选择年份"
            value-format="YYYY"
            @change="onSearch"
            style="width: 140px"
          />
        </el-form-item>

        <el-form-item label="年份(饼图)" v-show="chartView==='pie'">
          <el-date-picker
            v-model="pieYear"
            type="year"
            placeholder="选择年份"
            value-format="YYYY"
            @change="onSearch"
            style="width: 140px"
          />
        </el-form-item>

        <el-form-item label="月份(饼图)" v-show="chartView==='pie'">
          <el-select v-model="pieMonthNum" placeholder="选择月份" clearable @change="onSearch" style="width: 120px">
            <el-option v-for="m in 12" :key="m" :label="`${m}月`" :value="String(m)" />
          </el-select>
        </el-form-item>

        <el-form-item label="商户类型" v-show="chartView==='trend'">
          <el-select v-model="searchForm.merchantType" placeholder="全部类型" clearable @change="onSearch" style="width: 180px">
            <el-option v-for="mt in merchantTypeOptions" :key="mt" :label="mt" :value="mt" />
          </el-select>
        </el-form-item>

        <el-form-item label="异常筛选">
          <el-radio-group v-model="searchForm.abnormalStatus" @change="onSearch">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="0">正常</el-radio-button>
            <el-radio-button label="1">异常</el-radio-button>
          </el-radio-group>
        </el-form-item>

        

        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="container" v-show="chartView==='trend'">
      <el-card shadow="hover">
        <div id="trendChart" class="chart"></div>
      </el-card>
    </div>

    <div class="container pies" v-show="chartView==='pie'">
      <el-card shadow="hover">
        <div id="pieAmountChart" class="chart"></div>
      </el-card>
      <el-card shadow="hover">
        <div id="pieCountChart" class="chart"></div>
      </el-card>
    </div>

    <el-loading v-if="loading" text="加载中..." />
  </div>
</template>

<style scoped>
.report-page .container {
  margin-top: 15px;
  margin-bottom: 15px;
}
.search-form :deep(.el-form-item) {
  margin-right: 12px;
}
.chart {
  width: 100%;
  height: 380px;
}
.pies {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}
</style>